<?php


namespace app\api\controller\v27;

use app\api\controller\v13\Auth2;
use app\chat\LiveMessage as ChatLiveMessage;
use app\common\cachemodel\live\LiveAnchorInfo;
use app\common\cachemodel\live\LiveBroadcastPreview;
use app\common\cachemodel\live\LiveGift;
use app\common\cachemodel\live\LiveGoodsActivity;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\live\LiveSignHotDay;
use app\common\cachemodel\live\LiveUserContribution;
use app\common\cachemodel\live\LiveUserGiftBag;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\lib\exception\ApiException;
use app\common\model\User;
use think\Cache;
use think\Db;
use think\response\Json;

class Live extends Auth2
{

    /**
     * todo APP原生直播请求接口
     * 直播间详细
     * @return Json
     * @throws \Exception
     */
    public function liveRoom()
    {
        $live_id = input('live_id/d', 0);
        if ($this->user)
        {
            $uid = $this->user['id'];
        } else
        {
            $uid = 0;
        }
        $data = (new LiveRecordingInfo())->getLiveInfo($live_id, 0, $uid,false);
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取直播间推荐商品
     * @return Json
     * @throws \Exception
     */
    public function recommendGoods()
    {
        $live_id = input('live_id/d', 0);
        $live_record_id = input('live_record_id/d', 0);
        (new LiveRecordingInfo())->checkRecordId($live_id, $live_record_id);
        $type = input('type/d', 0);
        $liveGoodsModel = new LiveGoodsActivity();
        $goods = $liveGoodsModel->getAnchorGoods($live_id, $type, true);
        $data = $liveGoodsModel->resetGoods($goods, $live_id, $live_record_id, 1);
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 获取礼物列表
     * @return Json
     * @throws \Exception
     */
    public function getGiftList()
    {
        $giftList = (new LiveGift())->getListPage('', 'sort', [], 0);

        if ($this->user)
        {
            // 获取用户背包准币信息
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);
            $coin = (int)($user_coin['balance'] ?? 0);
            $hasCoinPwd = $user_coin['password'] ? 1 : 0;
        } else
        {
            $coin = 0;
        }

        $resGiftList = [];
        foreach ($giftList['data'] as $bagDatum)
        {
            $resGiftList[] = [
                'id' => (int)$bagDatum['id'],
                'name' => $bagDatum['name'],
                'type' => (int)$bagDatum['type'],
                'icon' => $bagDatum['img'],
                'coin' => (int)$bagDatum['coin'],
                'lottie' => $bagDatum['is_lottie'] > 0 ? json_decode($bagDatum['lottie'], true) : null
            ];
        }

        return show(config('code.success'), '请求成功', [
            'gift_list' => $resGiftList,
            'coin' => $coin,
            'has_coin_pwd' => $hasCoinPwd ?? 0,
        ]);
    }

    /**
     * 获取背包信息
     * @return Json
     * @throws \Exception
     */
    public function getBagInfo()
    {
        $giftList = (new LiveGift())->getListPage('', 'sort', [], 0);

        if ($this->user)
        {
            // 获取用户背包准币信息
            $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($this->user['id']);
            $coin = (int)($user_coin['balance'] ?? 0);
            $hasCoinPwd = $user_coin['password'] ? 1 : 0;
            // 获取用户背包信息
            $bagData = (new LiveUserGiftBag())->getUserGiftBag($this->user['id']);
        } else
        {
            $coin = 0;
            $bagData = [];
        }

        $bagList = [];
        foreach ($giftList['data'] as $bagDatum)
        {
            if (!isset($bagData[$bagDatum['id']]) || (int)$bagData[$bagDatum['id']]['num'] <= 0)
            {
                continue;
            }
            $bagList[] = [
                'id' => (int)$bagDatum['id'],
                'name' => $bagDatum['name'],
                'icon' => $bagDatum['img'],
                'have_num' => (int)$bagData[$bagDatum['id']]['num'],
                'lottie' => $bagDatum['is_lottie'] > 0 ? json_decode($bagDatum['lottie'], true) : null
            ];
        }

        return show(config('code.success'), '请求成功', [
            'coin' => $coin,
            'bag_list' => $bagList,
            'has_coin_pwd' => $hasCoinPwd ?? 0,
        ]);
    }

    /**
     * 直播间贡献总榜
     * @return Json
     * @throws ApiException
     */
    public function getConRankingList()
    {
        $live_id = input('live_id/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        if (!$live_id)
        {
            return show(config('code.error'), '请求异常');
        }

        if ($limit < 1 || $limit > 50)
        {
            $limit = 10;
        }

        if ($page < 1)
        {
            $page = 1;
        }

        $pageData = (new LiveUserContribution())->getContributionRanking($live_id, $page, $limit);

        $resData = [];
        foreach ($pageData['data'] as $uid => $rankingInfoItem)
        {
            $userInfo = current((new User())->batchGetUserInfo([$uid]));
            if ($userInfo)
            {
                $resData[] = [
                    'avatar' => $userInfo['avatar'],
                    'nickname' => $userInfo['nickname'],
                    'ranking' => $rankingInfoItem['ranking'],
                    'desc' => "贡献值：{$rankingInfoItem['contribution_value']}",
                ];
            }
        }

        $pageData['data'] = $resData;

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 获取热度日榜
     */
    public function getHotDayRankingList()
    {
        $liveId = input('live_id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        (new LiveRecordingInfo())->checkRecordId($liveId, $liveRecordId);
        $dayRankingList = (new LiveSignHotDay())->getDaySignList($liveId, $liveRecordId, date('Ymd'));

        for ($i = 1; $i < 13; $i++)
        {
            if (!isset($dayRankingList[$i]))
            {
                $dayRankingList[$i] = 0;
            }
        }
        arsort($dayRankingList);

        $resData = [];
        foreach ($dayRankingList as $sign => $hotNum)
        {
            if ($sign > 0)
            {
                $resData[] = [
                    'sign' => $sign,
                    'hot_num' => $hotNum . '热度'
                ];
            }
        }

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取在线时长和观看人数
     */
    public function getOnlineDurationAndNum()
    {
        $liveId = input('live_id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        (new LiveRecordingInfo())->checkRecordId($liveId, $liveRecordId);
        if (!$liveId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $liveRecordInfo = (new LiveRecordingInfo())->getInfoById($liveRecordId, ['live_start_time', 'content']);
        if (!$liveRecordInfo)
        {
            return show(config('code.error'), '请求异常');
        }

        $liveBroadcastPreview = (new LiveBroadcastPreview())->where('live_start_time', '>', $this->request->time())->order('live_start_time asc')->find();

        $liveInfo = (new LiveAnchorInfo())->getInfoById($liveId, ['avatar', 'name', 'intro']);
        // 观看人数
        $watchUserNum = Db::table('live_data.live_user_' . $liveId)->where('live_record_id', $liveRecordId)->group('uid')->count();
        $watchUserNum += 5; // 保证观看过的人数大于在线人数
        //增加基数
        $baseInfo = Cache::get($liveId . '-live_people_num-' . $liveRecordId);
        if ($baseInfo)
        {
            $baseInfo = json_decode($baseInfo, true);
            if ($baseInfo['type'] == 1)
            {
                $time = time();
                $timeEx = $time - $baseInfo['timestamp'];
                $duration = $baseInfo['duration'] * 60;
                if ($timeEx >= $duration)
                {
                    $watchUserNum += $baseInfo['num'] + ($baseInfo['start_base_num'] ?? 0);
                } else
                {
                    $num = (int)(($timeEx / $duration) * $baseInfo['num']) + ($baseInfo['start_base_num'] ?? 0);
                    $watchUserNum += $num;
                }
            } else
            {
                $onlineUserNum = ChatLiveMessage::getClientIdCountByGroup($liveId.'_app_user_group');
                $watchUserNum += ($onlineUserNum * $baseInfo['num'] - $onlineUserNum);
            }
        }

        return show(config('code.success'), '请求成功', [
            'avatar' => $liveInfo['avatar'] ?? '',
            'nickname' => $liveInfo['name'] ?? '',
            'intro' => $liveInfo['intro'] ?? '',
            'duration' => Sec2Time($this->request->time() - $liveRecordInfo['live_start_time']),
            'total_num' => ((int)$watchUserNum) . "人来看过",//获取在线人数
            'live_advance' => $liveBroadcastPreview['broadcast_content'] ?? '',
            'live_content' => $liveRecordInfo['content'],
        ]);
    }
}
